from flask import Blueprint, request,jsonify,redirect
import time
from utils.redis import r
from utils.comm import get_data
from flask_mail import Mail,Message
from flask import current_app as app

import re
from db import db1
bp_jyuser = Blueprint('jyuser', __name__)


def testmail(tou,ren,a):
    mail = Mail(app)
    msg = Message(tou,sender='qq1143028552@163.com',recipients=[ren])#发件人，收件人
    msg.html = a
    mail.send(msg)

@bp_jyuser.route('/useradd',methods=['POST','GET'])
def useradd():
    if request.method=='POST':
        data = get_data()
        mobie = data['mobie']
        m = data['email']
        reg = re.match('^1[3-9]\d{9}$',mobie)
        pat = re.match('^(\w)+(\.\w+)*@(\w)+((\.\w+)+)$',m)
        # try:
        if reg and pat:
            sql1 = '''select mobie,email from users where mobie="%s"'''%(data['mobie'])
            sql2 = '''select email from users where email="%s"'''%(data['email'])
            d = db1.find(sql1)
            x = db1.find(sql2)
            if not (d or x):
                sql = '''insert into users(name,password,email,mobie) 
                values("%s","%s","%s","%s")'''%(data['name'],data['password'],data['email'],data['mobie'])
                db1.update(sql)

                testmail('欢迎使用163', data['email'], "欢迎使用，点击以下<a href='http://localhost:5000/jyuser/validEmail?email=" + data[
                    'email'] + "'>链接</a>验证")
                # redis存过期时间 key 邮箱 value 当前时间  过期时间

                return jsonify({"code":200})
            else:
                return jsonify({"code":10012,'mes':'手机号或邮箱已注册'})
        else:
            return jsonify({"code":10010,'mes':'手机号不正确或邮箱不正确'})
        # except:
        #     return jsonify({"code":10011,'mes':'网络走丢了'})

@bp_jyuser.route('/validEmail')
def validEmail():
    #获取email
    email = request.args.get('email')
    #更新用户表
    sql = "update users set zt=1 where email='%s'"%(email)
    db1.update(sql)
    return redirect('http://localhost:8888')

#展示分类接口
@bp_jyuser.route('/show_cou',methods=['GET','POST'])
def show_cou():
    time.sleep(0.001)
    if request.method == 'GET':
        sql = '''select id,name from cates'''
        x = db1.fid_all(sql)
        return jsonify({"code":200,"list":x})

@bp_jyuser.route('/show_goods',methods=['GET','POST'])
def show_goods():
    if request.method=='GET':
        sql = '''select * from courses where shangxian=1'''
        d = db1.fid_all(sql)
        return jsonify({"code": 200, 'list': d})
    else:
        sql = '''select * from courses where shangxian=0'''
        d = db1.fid_all(sql)
        return jsonify({"code": 200, 'list': d})

from utils.comm import get_ali_object


@bp_jyuser.route('/pay')
def pay():
    alipay = get_ali_object()

    # 生成支付的url
    query_params = alipay.direct_pay(
        subject="test",  # 商品简单描述
        out_trade_no="myorder" + str(time.time()),  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=100,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return redirect(pay_url)

@bp_jyuser.route('/show_active',methods=['POST','GET'])
def show_active():
    if request.method=='GET':
        sql = '''select * from active'''
        a = db1.fid_all(sql)
        return jsonify({"code":200,'list':a})
    else:
        data = get_data()
        activeid = data['id']
        mobile = data['mobile']
        #qsl= 用户表
        sql = '''select * from users where mobie="%s"'''%(mobile)
        showUsers = db1.find(sql)
        #如果有这个用户
        if showUsers:
        #     #判断vip用户
            if showUsers['level'] == 2:
                #先查这个用户有没有参加本次会议
                sql4 = '''select id from active_record where active_id=%d and mobile="%s"'''%(int(data['id']),data['mobile'])
                #active_record表里查询这个用户参加的会议
                ar = db1.find(sql4)
                if ar:
                    return jsonify({"code":10011,'mes':'你已经参加本次会议'})
                elif not ar:
                    #查询会议表
                    sql3 = '''select * from active where id=%d'''% (int(activeid))
                    show_active = db1.find(sql3)
                    if show_active['use_count'] == 0:
                        return jsonify({"code":10010,"mes":"人数已满"})
                    #更新active_record表数据
                    else:
                        sql2 = '''insert into active_record(mobile,active_id,type,pay_status,money)
                        values("%s",%d,1,1,%.2f)'''% (data['mobile'],int(data['id']),float(show_active['price']))
                        db1.update(sql2)
                        #跟新会议表剩余人数
                        sql1 = '''update active set use_count=use_count-1 where id=%d''' % (int(activeid))
                        db1.update(sql1)
                        return jsonify({"code":200,"mes":"报名成功"})
            else:
                return jsonify({"code":10012,'mes':'请等待下次会议'})
        else:
            return jsonify({"code": 10013, 'mes': '网络不太好 下次再说'})


@bp_jyuser.route('/vip',methods=['POST','GET'])
def vip():
    if request.method == 'GET':
        sql = '''select * from vip_price order by type asc'''
        d = db1.fid_all(sql)
        return jsonify({"code":200,"list":d})

@bp_jyuser.route('/add_vip')
def add_vip():

    return jsonify({"code":200})











